<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="教练名称" prop="userName">
            <el-input
              v-model="queryParams.coachName"
              placeholder="请输入教练名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="教练号码" prop="phone">
            <el-input
              v-model="queryParams.coachPhone"
              placeholder="请输入教练手机号码"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="教练名称"
            align="center"
            key="coachName"
            prop="coachName"
            v-if="columns[0].visible"
          />
          <el-table-column
            label="教练邀请码"
            align="center"
            key="coachCode"
            prop="coachCode"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="教练手机号"
            align="center"
            key="coachPhone"
            prop="coachPhone"
            v-if="columns[2].visible"
            width="120"
          />
          <!--          <el-table-column-->
          <!--            label="教练图片"-->
          <!--            align="center"-->
          <!--            key="venueLocation"-->
          <!--            prop="venueLocation"-->
          <!--            v-if="columns[3].visible"-->
          <!--            width="130">-->
          <!--            <template slot-scope="scope">-->
          <!--                <el-image style="width: 60px; height: 60px" :src="'http://101.43.223.224:8765/image/getImageById?id=' + scope.row.coachImg"></el-image>-->
          <!--            </template>-->
          <!--         </el-table-column>-->
          <el-table-column
            label="教练图片"
            align="center"
            key="coachImg"
            prop="coachImg"
            width="130"
          >
            <template slot-scope="scope">
              <el-carousel height="80px" width="80px" v-if="scope.row.coachImg">
                <el-carousel-item
                  v-for="item in scope.row.coachImg.split(',')"
                  :key="item"
                >
                  <ImagePreview :src="String(item)"></ImagePreview>
                </el-carousel-item>
              </el-carousel>
              <el-tag v-else type="info">暂无数据</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="教练标签"
            align="center"
            key="coachFitness"
            prop="coachFitness"
            v-if="columns[4].visible"
            width="120"
          /> -->
          <el-table-column
            label="教练授课次数"
            align="center"
            key="coachTeachingTimes"
            prop="coachTeachingTimes"
            v-if="columns[4].visible"
            width="120"
          />
          <el-table-column
            label="教练信息"
            align="center"
            key="coachInformation"
            prop="coachInformation"
            v-if="columns[5].visible"
            width="120"
          />
          <el-table-column
            label="教练特长"
            align="center"
            key="coachSpecialty"
            prop="coachSpecialty"
            v-if="columns[6].visible"
            width="120"
          />
          <el-table-column
            label="教练经历"
            align="center"
            key="coachExperience"
            prop="coachExperience"
            v-if="columns[7].visible"
            width="120"
          />
          <!-- <el-table-column
            label="教练状态"
            align="center"
            key="delFlag"
            v-if="columns[9].visible"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.delFlag"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column> -->
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            v-if="columns[8].visible"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button
              >
              <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加教练配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="close">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="教练图片" >
          <el-upload
            class="avatar-uploader"
            action=""
            :multiple="true"
            :on-remove="handleRemove"
            :on-change="handlechange"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            accept=".jpg,.jpeg,.png,.gif"
            :auto-upload="false"
            :file-list="fileList"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" width="146" height="146" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="教练手机号(账号)" prop="coachPhone">
              <el-input v-model="form.coachPhone" placeholder="请输入教练手机号(账号)" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="教练信息" prop="coachInformation">
              <el-input v-model="form.coachInformation" placeholder="请输入教练信息" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教练特长" prop="coachSpecialty">
              <el-input v-model="form.coachSpecialty" placeholder="请输入教练特长" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教练经历" prop="coachExperience">
              <el-input v-model="form.coachExperience" placeholder="请输入教练经历" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教练名称" prop="coachName">
              <el-input
                v-model="form.coachName"
                placeholder="请输入教练名称"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addCoach,listCoach,updateVenue,deletecoachImg } from "@/api/coachManagement/index";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect },

  data() {
    return {
      imageUrl: "", //添加图片路径及其图片
      imgCarousel: "", //添加图片信息
      carouselupImg:'',//修改图片路径及其图片
      imgupCarousel:'',//修改图片信息
      // 是否显示修改弹出框
      upopen: false,
      // 遮罩层
      loading: true,
      // 图片集合
      fileList:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 课程选项
      roleOptions: [],
      // 标签选项
      popOptions: [],
      // 表单参数
      // 表单参数
      form: {
        delImageIds: undefined,
      },
      delImageIds: [],
      updateform: {
        updelImageIds: undefined,
      },
      updelImageIds: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      imgUrl: process.env.VUE_APP_IMG_BASE_URL,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        coachName: undefined,
        coachPhone: undefined,
        venueUniqueIdentifier: window.sessionStorage.getItem('venueUniqueIdentifier'),
      },
      // 列信息
      columns: [
        { key: 0, label: `教练名称`, visible: true },
        { key: 1, label: `教练邀请码`, visible: true },
        // { key: 2, label: `教练课程`, visible: true },
        { key: 2, label: `教练手机号`, visible: true },
        { key: 3, label: `教练图片`, visible: true },
        // { key: 4, label: `教练标签`, visible: true },
        { key: 4, label: `教练授课次数`, visible: true },
        { key: 5, label: `教练信息`, visible: true },
        { key: 6, label: `教练特长`, visible: true },
        { key: 7, label: `教练经历`, visible: true },
        // { key: 8, label: `教练价格`, visible: true },
        // { key: 9, label: `教练状态`, visible: true },
        { key: 8, label: `创建时间`, visible: true },
      ],
      // 表单校验
      rules: {
        coachName: [
          { required: true, message: "教练名称不能为空", trigger: "blur" },
          { max: 10, message: '最大长度为25', trigger: 'blur' }
        ],
        coachPhone: [
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" },
        ],
        coachInformation:[
          { max: 25, message: '最大长度为25', trigger: 'blur' }
        ],
        coachSpecialty:[
          { max: 25, message: '最大长度为25', trigger: 'blur' }
        ],
        coachSpecialty:[
          { max: 25, message: '最大长度为25', trigger: 'blur' }
        ]
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
  },
  methods: {

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listCoach(this.addDateRange(this.queryParams, this.dateRange)).then(
        (res) => {
          this.userList = res.data.data.content;
          this.total = res.data.data.totalSize;
          this.loading = false;
          console.log(this.userList)
        }
      );
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.coachName = undefined;
      this.queryParams.coachPhone = undefined;
      this.handleQuery();
    },
    // 图片上传之前的校验方法
    beforeAvatarUpload(file) {
      const isPNG = file.type === "image/png";
      const isJPG = file.type === "image/jpg";
      const isJPEG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isJPG && !isPNG && !isJPEG) {
        this.$message.error("上传图片只能是 JPG,格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },

    /** 新增按钮操作 */
    handleAdd() {
      // 重置表单
      this.reset();
      // this.idNameList();
      this.open = true;
      this.title = "添加教练信息";
    },
    // 添加教练操作
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.fileList.length > 5) {
            this.$modal.msgError("上传图片不能超过5张");
            return false;
          }
          var formData = new FormData();
          formData.set("courseId", this.form.courseId);
          formData.set("coachName", this.form.coachName);
          formData.set("coachPhone", this.form.coachPhone);
          formData.set("coachFitness", this.form.coachFitness);
          formData.set("coachInformation", this.form.coachInformation);
          if(this.form.coachSpecialty!= undefined){
            formData.set("coachSpecialty", this.form.coachSpecialty);
          }
          if(this.form.coachExperience != undefined) {
            formData.set("coachExperience", this.form.coachExperience);
          }
          formData.set("coachPrice", this.form.coachPrice);
          formData.set("venueUniqueIdentifier", window.sessionStorage.getItem('venueUniqueIdentifier'));
          // 多图片轮播图片
          if (this.fileList.length > 0) {
            this.fileList.forEach((item) => {
              formData.append("files", item.raw);
            });
          }
          if(this.form.id != '' && this.form.id != null && this.form.id != undefined){
            formData.set("id",this.form.id)
            /*for (const [key, value] of formData.entries()) {
              console.log(`${key}: ${value}`);
            }*/
            updateVenue(formData)
              .then((res) => {
                if (res.data) {
                  this.$message.success(res.data.data);
                  this.getList()
                  this.open = false
                } else {
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }else{
            // 使用 entries() 方法获取所有键值对
            /*for (const [key, value] of formData.entries()) {
              console.log(`${key}: ${value}`);
            }*/
            addCoach(formData)
              .then((res) => {
                if (res.data) {
                  this.$message.success(res.data.data);
                  this.getList()
                  this.fileList = [];
                  this.open = false
                } else {
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }

        } else {
          this.$message.error("请按照要求输入信息");
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleUpdate(row) {
      const that = this;
      this.reset();
      this.form = JSON.parse(JSON.stringify(row))
      const cocahImgs = row.coachImg;
      if (cocahImgs != 'null' && cocahImgs != undefined) {
        const cocahImgIds = cocahImgs.split(',');
        if (cocahImgIds.length > 0) {
          cocahImgIds.forEach(id => {
            if (id !== '') {
              this.fileList.push({ url: that.imgUrl + id, id: id });
            }
          });
        }
      }
      this.title = "修改教练信息";
      this.$nextTick(() => {
        this.open = true; // 打开弹窗
      });
    },

    // /** 删除按钮操作 */
    // handleDelete(row) {
    //   const userIds = row.id || this.ids;
    //   this.$modal
    //     .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    //     .then(function () {
    //       return delUser(userIds);
    //     })
    //     .then(() => {
    //       this.getList();
    //       this.$modal.msgSuccess("删除成功");
    //     })
    //     .catch(() => {});
    // },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handlechange(fileList) {
      this.fileList.push(fileList);
    },
    close(){
      this.fileList = [];
      this.imageUrl = "";
      this.open = false;
    },
    handleRemove(file) {
      // 删除照片
      if (file.id) {
        const coachImg = this.form.coachImg;
        let arrImgIds = coachImg.split(",");
        arrImgIds = arrImgIds.filter((item) => {
          return item !== file.id && item !== "";
        });
        this.delImageIds.push(file.id)
        const index = this.fileList.indexOf(file);
        if (index !== -1) {
          this.fileList.splice(index, 1);
        }
        this.form.coachImg = arrImgIds.join(",");
        deletecoachImg(this.form.id,file.id)
      } else {
        this.fileList = this.fileList.filter((item) => {
          return file.name !== item.name && file.url !== item.url;
        });
      }
    },
  },
};
</script>
